<?php

namespace app\service;

use app\core\Service;
use app\model\Goods;
use app\model\Income;
use app\model\Member;
use app\model\Order;
use think\facade\Db;

/**
 * @extends Service<IncomeService>
 */
class IncomeService extends Service
{
    public function getList($page, $limit, $searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['type']) && $searchQuery['type'] != '') {
            $w[] = ['type', '=', $searchQuery['type']];
        }
        if (!empty($searchQuery['types']) && $searchQuery['types'] != '') {
            $w[] = ['type', 'in', $searchQuery['types']];
        }

        if (!empty($searchQuery['orderNo']) && $searchQuery['orderNo'] != '') {
            $w[] = ['order_no', '=', $searchQuery['orderNo']];
        }
        if (!empty($searchQuery['timeValues'])) {
            if (!is_array($searchQuery['timeValues'])) {
                $timeValues = json_decode($searchQuery['timeValues']);
            } else {
                $timeValues = $searchQuery['timeValues'];
            }
            $w[] = ['create_time', 'between', $timeValues];
        }
        $map = Income::where($w)->page($page, $limit);
        $list = $map->select()->toArray();
        if ($list) {
            $member_ids = array_column($list, 'member_id');
            $goods_ids = array_column($list, 'goods_id');
            $MemberList = Member::where('member_id', 'in', $member_ids)->field('member_id,mobile,nick,avatar')->select()->toArray();
            $GoodsList = Goods::where('goods_id', 'in', $goods_ids)->field('goods_id,goods_name')->select()->toArray();
            $MemberList = array_column($MemberList, null, 'member_id');
            $GoodsList = array_column($GoodsList, null, 'goods_id');
            foreach ($list as &$value){
                $value['mobile'] = $MemberList[$value['member_id']]['mobile'];
                $value['goods_name'] = $GoodsList[$value['goods_id']]['goods_name'];
            }
        }

        return [
            'total' => $map->count(),
            'list' => $list,
        ];
    }

    //添加收益
    public function addIncome($data, $memberInfo, $type)
    {
        $member_id = 0;
        $where = [];
        if ($type == 1) {
            $data['commission'] = $data['price'] * ($data['primary_income'] / 100);
            $memberInfo['dis_commission'] = $memberInfo['dis_commission'] + $data['commission'];//分销佣金 一级二级分销佣金
            $member_id = $memberInfo['pid'];
        } elseif ($type == 2) {
            $data['commission'] = $data['price'] * ($data['secondary_income'] / 100);
            $memberInfo['dis_commission'] = $memberInfo['dis_commission'] + $data['commission'];//分销佣金 一级二级分销佣金
            $member_id = $memberInfo['pid'];
        } elseif ($type == 3) {
            $data['commission'] = $data['daily_income'];
            $memberInfo['commission'] = $memberInfo['commission'] + $data['commission'];//每日收益积分+退购转换积分
            $member_id = $memberInfo['member_id'];
            $where[] = ['date', '=', date('Y-m-d', time())];
        }
        $memberInfo['amount'] = $memberInfo['amount'] + $data['commission'];//总收益
        $where[] = ['type', '=', $type];
        $where[] = ['order_id', '=', $data['order_id']];
        $info = Income::where($where)->find();
        if ($info) {
            return false;
        }
        Db::startTrans();
        $rs = Income::create([
            'commission' => $data['commission'],
            'member_id' => $member_id,
            'type' => $type,
            'goods_id' => $data['goods_id'],
            'order_id' => $data['order_id'],
            'order_no' => $data['order_no'],
            'price' => $data['price'],
            'date' => date('Y-m-d', time()),
        ]);
        if (!$rs) {
            Db::rollback();
            return false;
        }
        if ($type == 3) {
            $Order = Order::where(['order_id' => $data['order_id']])->find();
            $orderInfo = $Order->toArray();
            $commission = $orderInfo['commission'] + $data['commission'];
            $rs = $Order->save(['commission' => $commission]);
            if (!$rs) {
                Db::rollback();
                return false;
            }
        }
        $rs = Member::where('member_id', $member_id)->save($memberInfo);
        if (!$rs) {
            Db::rollback();
            return false;
        }
        Db::commit();
        return true;
    }

    public
    function getCommission($member_id)
    {
        $w = [];
        $w[] = ['member_id', '=', $member_id];
        $w[] = ['type', 'in', [1, 2]];
        $commission = Income::where($w)->sum('commission');
        return $commission ?: 0.00;
    }

    public function getIncomeListByOrder($page, $limit, $searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['type']) && $searchQuery['type'] != '') {
            $w[] = ['type', '=', $searchQuery['type']];
        }
        if (!empty($searchQuery['order_id']) && $searchQuery['order_id'] != '') {
            $w[] = ['order_id', '=', $searchQuery['order_id']];
        }
        if (!empty($searchQuery['member_id']) && $searchQuery['member_id'] != '') {
            $w[] = ['member_id', '=', $searchQuery['member_id']];
            $Member = Member::where(['member_id' => $searchQuery['member_id']])->field('member_id,pid,mobile,nick,avatar,level')->find()->toArray();
        }
        $map = Income::where($w)->page($page, $limit);
        $list = $map->select();
        foreach ($list as &$value) {
            $value['nick'] = !empty($Member['nick']) ? $Member['nick'] : '';
            $value['avatar'] = !empty($Member['avatar']) ? $Member['avatar'] : '';
        }
        return [
            'total' => $map->count(),
            'list' => $list,
        ];
    }

    public function list($page, $limit, $searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['type']) && $searchQuery['type'] != '') {
            $w[] = ['type', '=', $searchQuery['type']];
        }
        $map = Income::where($w)->page($page, $limit);
        return [
            'total' => $map->count(),
            'list' => $map->select(),
        ];
    }

}